package com.open.free.boot.core.interceptor;

import com.open.free.boot.common.jwt.JWTUtils;
import com.open.free.boot.core.annotation.JwtIgnore;
import com.open.free.boot.core.exception.AccessException;
import com.open.free.boot.core.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Faye.Wang
 * @version 1.0
 * @date 2020/9/4 16:22
 * @Description 访问token验证，接口调用token访问
 */
public class AccessServerInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(AccessServerInterceptor.class);

    @Value("${jwt.access.token.secret}")
    private String jwtAccessSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod =(HandlerMethod)handler;
            JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
            if(jwtIgnore!=null){
                return true;
            }
        }

        String accessToken = request.getHeader(JWTUtils.AUTH_HEADER_KEY);

        System.out.println(accessToken);

        if(StringUtils.isBlank(accessToken)){
            logger.info("## authHeader ERROR= {}", "非法请求");
            throw new AccessException("非法请求");
        }

        if(!JWTUtils.verify(accessToken,jwtAccessSecret)){
            logger.info("## authHeader ERROR= {}", "非法请求");
            throw new AccessException("非法请求");
        }
        return true;
    }
}
